package SGUI

import (
	. "SGEngine2"
	"bytes"
	"dom4g"
	"fmt"
	"io/ioutil"
	"os"
	"strconv"
	"strings"
	"text/template"
)

var SGMLGlobal *_SGMLGlobal
var addTopi = 0

type GenWidgetFunc func(*dom4g.Element, *Node, *TopWidget, IWidget) IWidget
type SGMLEvent func(*Node)

type _SGMLGlobal struct {
	SGMLTypes map[string]SGMLElemInfo
}

const (
	SGMLElemType_Normal = 0
	SGMLElemType_Custom = 1
)

type SGMLElemInfo struct {
	GenFunc          GenWidgetFunc
	ElemType         int
	CustomChildParse func(IWidget, *dom4g.Element)
}

func (this *_SGMLGlobal) Init() {
	SGMLGlobal = new(_SGMLGlobal)
	SGMLGlobal.SGMLTypes = make(map[string]SGMLElemInfo)
	SGMLGlobal.SGMLTypes["Rectange"] = SGMLElemInfo{GenRectangeByXML, SGMLElemType_Normal, nil}
	SGMLGlobal.SGMLTypes["Text"] = SGMLElemInfo{GenTextByXML, SGMLElemType_Normal, nil}
	SGMLGlobal.SGMLTypes["Canvas"] = SGMLElemInfo{GenCanvasByXML, SGMLElemType_Normal, nil}
	SGMLGlobal.SGMLTypes["Img"] = SGMLElemInfo{GenImageByXML, SGMLElemType_Normal, nil}
	SGMLGlobal.SGMLTypes["StackPanel"] = SGMLElemInfo{GenStackPanelByXML, SGMLElemType_Normal, nil}
	SGMLGlobal.SGMLTypes["DockPanel"] = SGMLElemInfo{GenDockPanelByXml, SGMLElemType_Normal, nil}
	SGMLGlobal.SGMLTypes["TreeView"] = SGMLElemInfo{GenTreeByXml, SGMLElemType_Custom, treeChildParse}

}

func (this *_SGMLGlobal) LoadTopWidgetNode(fileName string, tplvalue interface{}, parentPath string) *TopWidget {
	zn := ZeroNode()
	tw := this.LoadTopWidget(fileName, tplvalue, zn, parentPath)
	zn.Add(tw)
	return tw
}

func (this *_SGMLGlobal) LoadTopWidget(fileName string, tplvalue interface{}, node *Node, parentPath string) *TopWidget {
	if UIScript.JsEngine == nil {
		UIScript.Init()
	}

	t := &TopWidget{FilePath: fileName}
	t.WidgetIds = make(map[string]IWidget)
	t.SGMLFunc = make(map[string]SGMLEvent)
	t.ImportWidget = make(map[string]string)
	t.WidgetClasses = make(map[string]*Array)

	t.UserData = tplvalue
	DotArr := strings.Split(fileName, ".")
	f, err := os.Open(t.FilePath)
	if err != nil {
		fmt.Println(err)
	}
	bs, _ := ioutil.ReadAll(f)
	t.XmlStr = "<Root>" + string(bs) + "</Root>"

	Ext := DotArr[len(DotArr)-1]
	if Ext == "tpl" {
		tpl, err := template.New(fileName).Parse(t.XmlStr)
		if err != nil {
			fmt.Println(err)
		}
		b := bytes.NewBuffer(make([]byte, 0))
		err2 := tpl.Execute(b, tplvalue)
		if err != nil {
			fmt.Println(err2)
		}
		t.XmlStr = string(b.String())
	}

	t.WidgetInfo.Width = float32(RootView.Width)
	t.WidgetInfo.Height = float32(RootView.Height)
	doc, err := dom4g.LoadByXml(t.XmlStr)
	if err != nil {
		fmt.Println(err)
	}

	twName := "TW" + strconv.Itoa((addTopi))
	addTopi += 1
	UIScript.JsEngine.Set(twName, t)
	scriptStrHead := `
	 (function(){
         This = new TopWidget("` + DotArr[0] + `",` + twName + `)
	 `

	node.Add(t)
	newNode := ZeroNode()
	node.AddChild(newNode)

	for i := 0; i < len(doc.Root().AllNodes()); i++ {
		if doc.Root().AllNodes()[i].Name() == "script" {
			RunStr := scriptStrHead + doc.Root().AllNodes()[i].Value + `	 })();`
			_, err := UIScript.JsEngine.Run(RunStr)
			if err != nil {
				fmt.Println(RunStr)
				fmt.Println(err)
			}
		} else if doc.Root().AllNodes()[i].Name() == "import" {
			t.LoadChild(doc.Root().AllNodes()[i])
		} else {
			t.AddWidgetByXML(doc.Root().AllNodes()[i], newNode, t)
		}
	}
	t.WidthType = Widget_Auto
	t.HeightType = Widget_Auto

	return t
}

func init() {
	SGMLGlobal.Init()
}
